#!/usr/bin/env python

# This script retrieves metadata about a cd from cddb, allows you to edit, 
# writes a CUE sheet, rips the cd audio using cdparanoia, encodes to FLAC, 
# then embeds the metadata as FLAC tags.

name = 'AudioArchiver'
ver = '0.1b'

filename = 'AlbumPerformer - AlbumYear - AlbumTitle'
flacdir = '/home/code-breaker/flacs'
cuedir = '/home/code-breaker/flacs/CUEs-Covers' # Cover image will be copied too, if present. If this is '', cue will be deleted.

chooseFLAC = True # If rip == False, you can browse for a FLAC file to write tags to
chooseCover = True # If true, browse for image

import sys, os, shutil
from sys import argv as argv
from tkFileDialog import askopenfilename
from CueParser import CueParser
cue = CueParser()
from mutagen.flac import FLAC as md
  
workingpath = os.path.abspath(os.path.dirname(argv[0]))

cuefilename = askopenfilename(filetypes=(('CUE Files', '*.cue'),("All Files", "*")), title="Choose CUE File")
if cuefilename:
  try:
    import codecs
    fin = codecs.open(filename, "r", "utf8")
    contents = fin.read()
  finally:
    fin.close()
FLACFilename = cue.getSoundFileFromCue(contents)
metadata = md(FLACFilename)
thissamples = metadata.info.total_samples
thissr = metadata.info.sample_rate
cue.getMetadataFromCue(contents,metadata.info.total_samples,metadata.info.sample_rate)

if (chooseCover):
  jpgfilename = askopenfilename(filetypes=(('jpg Files', '*.jpg'),("All Files", "*")), title="Choose cover for " + cue.title)
  if jpgfilename:
    shutil.copy(jpgfilename, os.path.join(workingpath, filename + ".jpg"))

shutil.copy(FLACFilename, os.path.join(workingpath, filename + ".flac"))

print "writing tags..."
os.system("python ./writeFLACTags.py \"" + os.path.join(workingpath, filename + ".cue") + "\"")
print "moving..."
shutil.copy(os.path.join(workingpath, filename + ".flac"), flacdir)
os.unlink(os.path.join(workingpath, filename + ".flac"))

if (cuedir != ''):
  shutil.copy(os.path.join(workingpath, filename + ".cue"), cuedir)
  os.unlink(os.path.join(workingpath, filename + ".cue"))
  if os.path.exists(os.path.join(workingpath, filename + ".jpg")):
    shutil.copy(os.path.join(workingpath, filename + ".jpg"), cuedir)
    os.unlink(os.path.join(workingpath, filename + ".jpg"))


